import createRequest, { RequestConfig } from './http'

const httpRequest = createRequest()

export type HttpRequestHook = {
    beforeRequest: (config: RequestConfig) => RequestConfig
    afterResponse: (data: any) => [0 | 1, any]
}

export const init = (options: RequestConfig, hooks?: HttpRequestHook) => {
    httpRequest.init(options)
    httpRequest.useRequestInterceptor(
        (config) => {
            if (hooks && typeof hooks?.beforeRequest === 'function') {
                const newConfig = hooks.beforeRequest(config)
                return Promise.resolve(newConfig)
            }
            return Promise.resolve(config)
        },
        async (error) => {
            console.error('获取请求配置错误', error)
            return Promise.resolve({})
        }
    )
    httpRequest.useResponseInterceptor(
        (response) => {
            const { statusCode, data } = response
            const isOk = statusCode >= 200 && statusCode <= 300
            if (!isOk) {
                console.error('请求错误,错误的状态码:', statusCode, response)
                return Promise.resolve([0, null])
            }
            if (hooks && typeof hooks?.beforeRequest === 'function') {
                const [error, newData] = hooks.afterResponse(data)
                return Promise.resolve([error, newData])
            }
            return Promise.resolve([1, data])
        },
        async (error) => {
            console.error('请求错误：', error)
            return Promise.resolve([0, null])
        }
    )
}

export const post = function <T extends Record<string, any>>(
    url: string,
    params?: T,
    config?: RequestConfig
) {
    return httpRequest.request({ url, method: 'POST', data: params, ...config })
}
export const get = function <T extends Record<string, any>>(
    url: string,
    params?: T,
    config?: RequestConfig
) {
    return httpRequest.request({ url, method: 'GET', params: params, ...config })
}
